package com.home.livedata

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.Timer
import java.util.TimerTask

class TimeLiveDataViewModel : ViewModel() {
    private lateinit var timer: Timer
    private var currentSecond: MutableLiveData<Int>? = null

    fun getCurrentSecond(): MutableLiveData<Int> {
        if (currentSecond == null) {
            currentSecond = MutableLiveData<Int>(0)
        }
        return currentSecond as MutableLiveData<Int>
    }

    fun startTiming() {
        timer = Timer()
        var timerTask: TimerTask = object : TimerTask() {
            override fun run() {
                currentSecond?.let {
                    it.value = it.value!! + 1
                    onTimeChangeListener.let {
                        currentSecond!!.value?.let { it1 -> it.onTimeChange(it1) }
                    }
                }
            }
        }
        timer.schedule(timerTask, 1000, 1000)
        /*timerTask {
            currentSecond++
            onTimeChangeListener.let {
                it.onTimeChange(currentSecond)
            }
            timer.schedule(this,1000,1000)
        }*/
    }

    interface OnTimeChangeListener {
        fun onTimeChange(second: Int)
    }

    private lateinit var onTimeChangeListener: OnTimeChangeListener
}